import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

// 布局组件
const Layout = () => import('../views/layout.vue')
// 首页
const Index = () => import('../views/home')
// 问答
const Question = () => import('../views/question')
// 视频
const Video = () => import('../views/video')
// 个人中心
const Profile = () => import('../views/profile')
// 编辑个人资料
const User = () => import('../views/user/edit.vue')
// 小智
const Chat = () => import('../views/user/chat.vue')
// 登录
const Login = () => import('../views/login')
// 搜索中心
const Search = () => import('../views/search/index.vue')
// 搜索结果
const Result = () => import('../views/search/result.vue')
// 详情
const Article = () => import('../views/article')

const routes = [
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: '/',
        component: Index,
        meta: { isKeepAlive: true }
      },
      {
        path: '/question',
        component: Question
      },
      {
        path: '/video',
        component: Video
      },
      {
        path: 'user',
        component: Profile
      }
    ]
  },
  {
    path: '/user/profile',
    component: User
  },
  {
    path: '/user/chat',
    component: Chat
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/search',
    component: Search
  },
  {
    path: '/search/result',
    component: Result
  },
  {
    path: '/article/:id',
    component: Article,
    meta: { isKeepAlive: true }
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  const { user } = store.state
  if (to.path.startsWith('/user') && !user.token) {
    next(`/login?redirectUrl=${to.path}`)
  } else {
    next()
  }
})

export default router
